package com.enjoy.book.dao;


import com.enjoy.book.bean.Record;
import com.enjoy.book.util.DBHelper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 赵洋
 */
public class RecordData implements  RecordDao{
    QueryRunner runner = new QueryRunner();
    @Override
    public List<Record> getRecordByBookId(long bookId) throws SQLException {
        Connection conn = DBHelper.getConnection();
        String sql ="select * from record where bookId= ?";
        List<Record> records = runner.query(conn,sql,new BeanListHandler<Record>(Record.class),bookId);
        DBHelper.close(conn);
        return records;

    }
    @Override
    public List<Record> getRecordByMemberId(long memberId) throws SQLException {
        Connection conn = DBHelper.getConnection();
        String sql ="select * from record where memberId= ? and backDate is null";
        List<Record> records = runner.query(conn,sql,new BeanListHandler<Record>(Record.class),memberId);
        return records;
    }
    @Override
    public  int modify(double deposit, long userId, long id) throws SQLException {
        String sql = "update  record set backDate = CURRENT_DATE,deposit = ?,userId = ? where id=?";
        Connection conn = DBHelper.getConnection();
        int count = runner.update(conn,sql,deposit,userId,id);
        DBHelper.close(conn);
        return count;
    }


    @Override
    public int add(long memberId, long bookId, double deposit, long userId) throws SQLException {
        String sql="insert into record values(null,?,?,CURRENT_DATE,null,?,?,'978-7-302-12260-9')";
        Connection conn = DBHelper.getConnection();
        int count = runner.update(conn,sql,memberId,bookId,deposit,userId);
        DBHelper.close(conn);
        return count;
    }

    @Override
    public Record getById(long recordId) throws SQLException {
        Connection conn = DBHelper.getConnection();
        String sql ="select * from record where id=?";
        Record record = runner.query(conn,sql,new BeanHandler<Record>(Record.class),recordId);
        DBHelper.close(conn);
        return record;
    }
}
